package chen.web.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * 设置浏览器缓存，在没有配置前端服务器（比如nginx）时使用，用于缓存静态内容
 * 可配置参数max-age
 * 
 * @author chen
 *
 */
public class BrowserCache implements Filter {

	private static int MaxAge = 6000;
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletResponse response = (HttpServletResponse) arg1;
		response.setHeader("Cache-Control", "max-age=" + MaxAge);
		chain.doFilter(arg0, arg1);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		String maxAge = config.getInitParameter("max-age");
		if(maxAge != null && maxAge.trim().length() > 0){
			MaxAge = Integer.parseInt(maxAge);
		}
	}

}
